package com.sosee.cgfw.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONArray;
import com.sosee.cgfw.R;
import com.sosee.cgfw.adapter.*;
import com.sosee.cgfw.entity.BrandJson;
import com.sosee.cgfw.entity.JsonData;
import com.sosee.cgfw.interfac.ScheduleInterface;
import com.sosee.cgfw.utils.Constans;
import com.sosee.cgfw.utils.LogUtils;
import com.sosee.cgfw.utils.Utils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Thinkpad on 2016/2/1.
 * //活动日程activity
 */
public class ScheduleActivity extends Activity implements ScheduleInterface, AdapterView.OnItemClickListener {
    private ListView lv;//活动列表
    private ScheduleAdapter myadapter;
    private HttpUtils httpUtils;
    private List<JsonData> list;//活动日程集合
    private TextView tv_date;//日期选择
    String time="2015-10-30";
    public static int i=0;//记录当前显示时间 位置
    MyCollection collection;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_schedule);
        httpUtils=new HttpUtils();
        httpUtils.configCurrentHttpCacheExpiry(10);
        showDay();
        collection=new MyCollection();
        if(Constans.userID!=null&&!Constans.userID.trim().equals("")){
            getShouCang();//获取收藏列表
        }


        initView();
        initData();
    }


    public void initView(){
        lv= (ListView) findViewById(R.id.lv);
        myadapter=new ScheduleAdapter(this);
        myadapter.setAnInterface(this);
        lv.setOnItemClickListener(this);
        lv.setAdapter(myadapter);
        tv_date= (TextView) findViewById(R.id.tv_date_se);

    }

    //处理返回和品牌点击事件
    public void onClick(View view){
        int id=view.getId();
        switch (id){
            case R.id.ig_back:
                finish();
                break;
            case R.id.ig_pinpai:
                Intent intent=new Intent(this, com.sosee.cgfw.adapter.MainActivity.class);
                startActivity(intent);
                finish();
                break;
        }
    }
    public void initData(){
        Collections.sort(Utils.list_date);
        tv_date.setText(Utils.list_date.get(i));
        time=Utils.list_date.get(i);
        getList(time, null);
        getPinPai();
    }
    //联网获取已收藏列表
    public void getShouCang(){
        httpUtils.send(HttpRequest.HttpMethod.GET, Constans.URL_SHOUCANG +Constans.userID+ "&showID=-1", new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                try {
                    JSONObject obj=new JSONObject(responseInfo.result);
                    String status=obj.getString("status");
                    if("success".equals(status)){
                        String slist=obj.getString("data");
                        Utils.list_shoucang.clear();
                        Utils.list_shoucang.addAll(Utils.stringToList(slist, ","));
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {
                Utils.showToast(getString(R.string.internet_error));
            }
        });

    }



    //联网获取活动日程
    public void getList(String time,String location){
        String url=Constans.URL_SCHEDULE+"?date="+time;
        if(location!=null&&!"".equals(location)){
            url=url+"&loc="+location;
        }

        httpUtils.send(HttpRequest.HttpMethod.GET, url, new RequestCallBack<String>() {


            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                //获取网络数据 刷新listview
                list = Utils.getSchedule(responseInfo.result);
                Collections.sort(list, collection);
                myadapter.setList(list);
                myadapter.notifyDataSetChanged();
            }

            @Override
            public void onFailure(HttpException e, String s) {
                Utils.showToast("" + e.getMessage());

            }
        });
    }

    //展开菜单按钮点击事件
    @Override
    public void onZhankaiClick(int position,boolean zhanKai) {
        if(zhanKai){
            Utils.list_menu.add(position+"");
            myadapter.notifyDataSetChanged();
        }else{
            Utils.list_menu.remove(position+"");
            myadapter.notifyDataSetChanged();
        }

    }
    //item点击事件
    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        Intent intent=new Intent(ScheduleActivity.this,ScheduleDetailActivity.class);
        JsonData data= (JsonData) adapterView.getItemAtPosition(i);
        intent.putExtra("detail",data);
        startActivity(intent);
        finish();
    }


    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    //显示举办地点按钮点击事件
    public void showAddress(View view){
        showPopUp(view);
    }
    //在控件上方显示popupwindow
    PopupWindow popupWindow;
    private void showPopUp(View v) {
        LinearLayout layout= (LinearLayout) View.inflate(this,R.layout.item_pop_address,null);

        popupWindow = new PopupWindow(layout, ViewGroup.LayoutParams
                .MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);

        layout.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        int popupWidth = layout.getMeasuredWidth();
        int popupHeight = layout.getMeasuredHeight();



        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        int[] location=new int[2];
        v.getLocationOnScreen(location);


        LogUtils.log_E(location[1] + "");
        LogUtils.log_E(popupWindow.getHeight() + "");

        popupWindow.showAtLocation(v, Gravity.NO_GRAVITY, location[0], location[1] - popupHeight);
    }
    //重写返回事件
    @Override
    public void onBackPressed() {
        LogUtils.log_E("finish");
        finish();//结束当前activity
    }

    //日期回退点击事件
    public void pre(View view){
        if(i<1){
            i=0;
        }else{
            i=i-1;
        }
        time=Utils.list_date.get(i);
        tv_date.setText(time);
        getList(time, null);
    }
    //日期向后点击事件
    public void next(View view){
        if(i!=Utils.list_date.size()-1){
            i=i+1;
        }
        time=Utils.list_date.get(i);
        tv_date.setText(time);
        getList(time, null);
    }
    //变更日期 并转换为string
    public String dateChangData(String date,int i){

        String str=tv_date.getText().toString();
        SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd");
        Date d=null;
        try {
            d =sdf.parse(str);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        Calendar calendar = Calendar.getInstance();

        calendar.setTime(d);
        calendar.add(Calendar.DAY_OF_MONTH,i);
        SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd");
        String t = s.format(calendar.getTime());
        tv_date.setText(t);
        time=t;
        return t;
    }

    //根据地址查询 活动日程
    public void click(View view){
        RelativeLayout ll= (RelativeLayout) view;
        TextView tv_loc= (TextView) ll.getChildAt(0);
        String loc=tv_loc.getText().toString();
        if(loc.equals("所有场地")){
            loc="";
        }
        getList(time,loc);
        if(popupWindow!=null){
            popupWindow.dismiss();
        }
    }
    //处理 utils中保存的菜单展开项
    @Override
    protected void onDestroy() {
        super.onDestroy();
        //清楚数据
        Utils.list_menu.clear();
    }
























    private Map<String,List<String>> pin_map=new HashMap<String, List<String>>();
    //获取品牌列表
    public void getPinPai(){
        httpUtils.send(HttpRequest.HttpMethod.GET, Constans.URL_LOGO_LIST, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {

                String result = responseInfo.result;
                List<BrandJson> blist = JSONArray.parseArray(result, BrandJson.class);
                if (blist != null) {
                    try{
                        Utils.pinList.clear();
                        Utils.letterList.clear();
                        for (int i = 0; i < blist.size(); i++) {
                            String name="";
                            List<String> pic_list=new ArrayList<String>();
                            LogUtils.log_E("BrandNamr开始");
                            name= blist.get(i).getData().getName();
                            LogUtils.log_E("BrandNamr结束");
                            List<String> pic=blist.get(i).getData().getPic();
                            if(pic!=null&&pic.size()>0){
                                for (int n=0;n<pic.size();n++){
                                    String p=pic.get(n);
                                    pic_list.add(p);
                                    Utils.letterList.add(Utils.getPinYinHeadChar(name).toUpperCase());
                                    Utils.pinList.add(p);
                                    Utils.bran_list.put(p, blist.get(i));
                                }
                            }
                            if(!pin_map.containsKey(Utils.getPinYinHeadChar(name).toUpperCase())){
                                pin_map.put(Utils.getPinYinHeadChar(name).toUpperCase(),pic_list);
                            }else{
                                List<String> tlist=pin_map.get(pin_map.put(Utils.getPinYinHeadChar(name).toUpperCase(),pic_list));
                                if(pic_list!=null&&tlist!=null){
                                    tlist.addAll(pic_list);
                                }
                                pin_map.put(Utils.getPinYinHeadChar(name).toUpperCase(),tlist);
                            }

                            LogUtils.log_E("测试排序："+Utils.getPinYinHeadChar(name).toUpperCase()+name);
                        }
                        for (int i=0;i<Utils.letterList.size();i++){
                            LogUtils.log_E(Utils.letterList.get(i));
                        }
                    }catch (Exception e){
                        LogUtils.log_E("品牌报错"+e.toString());
                    }
                } else {
                    Utils.showToast("blist====null");
                }
            }
            @Override
            public void onFailure(HttpException e, String s) {

            }
        });
    }


    //默认显示最近的时间
    public void showDay(){

        Calendar ca = Calendar.getInstance();
        int year = ca.get(Calendar.YEAR);//获取年份
        int month=ca.get(Calendar.MONTH)+1;//获取月份
        int day=ca.get(Calendar.DATE);//获取日
        String mo="";
        String da="";
        if(month<10){
            mo="0"+month;
        }else{
            mo=month+"";
        }
        if(day<10){
            da="0"+day;
        }else{
            da=day+"";
        }
        LogUtils.log_E(year+"-"+mo+"-"+da);
        String date=year+"-"+mo+"-"+da;
        int position=Utils.list_date.indexOf(date);
        if(position>-1){
            i=position;
        }else{
            if(date.compareTo(Utils.list_date.get(0))<=0){
                i=0;
            }else{
                if (date.compareTo(Utils.list_date.get(Utils.list_date.size()-1))>0){
                    i=Utils.list_date.size()-1;
                }
            }
        }
    }





    public class MyCollection implements Comparator<JsonData>{

        @Override
        public int compare(JsonData lhs, JsonData rhs) {
            String time1=lhs.getData().getStart_time();
            String time2=rhs.getData().getStart_time();

            return time1.compareTo(time2);
        }
    }



















}
